package cn.edu.jju.psytest.service;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.jju.psytest.model.entity.Question;
import cn.edu.jju.psytest.model.entity.Quiz;
import cn.edu.jju.psytest.persist.QuizDao;

@SuppressWarnings("restriction")
@Service
@Transactional(readOnly = true)
public class QuizService {

	private QuizDao quizDao;

	@Transactional(readOnly = false)
	public void createQuiz() {
		Quiz quiz = new Quiz();
		quiz.setName("心理健康测试问卷");
		quiz.setDescription("暂无");
		quiz.setCreatedDate(new Date());

		HSSFWorkbook wb = null;
		try {
			wb = new HSSFWorkbook(this.getClass().getResourceAsStream(
					"/../../upload/quiz.xls"));
		} catch (IOException e) {
			e.printStackTrace();
		}

		HSSFSheet sheet = wb.getSheetAt(0);
		int rowNum = sheet.getPhysicalNumberOfRows();
		for (int i = 0; i < rowNum; i++) {
			Question q = new Question();
			HSSFRow row = sheet.getRow(i);
			HSSFCell cell = row.getCell(0);
			q.setContent(cell.getStringCellValue());
			q.setOptions("没有:很轻:中度:偏重:严重");
			q.setQuiz(quiz);
			quiz.getQuestions().add(q);
		}
		quizDao.saveQuiz(quiz);
	}

	public Quiz loadQuiz(int quizId) {
		return quizDao.loadQuiz(quizId);
	}

	public List<Quiz> loadQuizzes() {
		return quizDao.loadQuizzes();
	}

	/**
	 * Getters And Setters
	 */
	public QuizDao getQuizDao() {
		return quizDao;
	}

	@Resource
	public void setQuizDao(QuizDao quizDao) {
		this.quizDao = quizDao;
	}
}
